package services

import (
    "context"
    "errors"
    "saasems/models"
    "sync"
)

type UserService struct {
    users map[string]*models.User
    mu    sync.RWMutex
}

func NewUserService() *UserService {
    return &UserService{
        users: make(map[string]*models.User),
    }
}

// 系统维护管理员创建用户
func (s *UserService) CreateSystemUser(ctx context.Context, username, password string, level models.UserLevel, permissions []models.Permission) (*models.User, error) {
    s.mu.Lock()
    defer s.mu.Unlock()

    if _, exists := s.users[username]; exists {
        return nil, errors.New("用户已存在")
    }

    user := &models.User{
        Username:    username,
        Password:    password,
        Level:       level,
        Permissions: permissions,
        IsSystem:    true,
    }

    s.users[username] = user
    return user, nil
}

// 租户超级管理员创建用户
func (s *UserService) CreateTenantUser(ctx context.Context, tenantID, username, password string, level models.UserLevel, permissions []models.Permission) (*models.User, error) {
    s.mu.Lock()
    defer s.mu.Unlock()

    if _, exists := s.users[username]; exists {
        return nil, errors.New("用户已存在")
    }

    user := &models.User{
        Username:    username,
        Password:    password,
        Level:       level,
        Permissions: permissions,
        TenantID:    tenantID,
        IsSystem:    false,
    }

    s.users[username] = user
    return user, nil
}

// 验证用户权限
func (s *UserService) CheckPermission(username string, permission models.Permission) bool {
    s.mu.RLock()
    defer s.mu.RUnlock()

    user, exists := s.users[username]
    if !exists {
        return false
    }

    for _, p := range user.Permissions {
        if p == permission {
            return true
        }
    }
    return false
}